package com.example.amusic.service

import android.app.PendingIntent
import android.app.Service
import android.app.TaskStackBuilder
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Binder
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import androidx.annotation.OptIn
import androidx.media3.common.AudioAttributes
import androidx.media3.common.C
import androidx.media3.common.MediaItem
import androidx.media3.common.PlaybackException
import androidx.media3.common.Player
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.DefaultRenderersFactory
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
import androidx.media3.session.CommandButton
import androidx.media3.session.DefaultMediaNotificationProvider
import androidx.media3.session.MediaController
import androidx.media3.session.MediaSession
import androidx.media3.session.MediaSessionService
import androidx.media3.session.SessionCommand
import androidx.media3.session.SessionToken
import com.example.amusic.MainActivity
import com.example.amusic.MyApp
import com.example.amusic.R
import com.example.amusic.service.v3.MusicNotificationProvider
import com.example.amusic.utils.IntentUtils
import com.example.amusic.utils.MediaSessionConstants
import com.google.common.collect.ImmutableList
import com.google.common.util.concurrent.MoreExecutors
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update

object MEDIA_NOTIFICATION {
    const val NOTIFICATION_ID = 200
    const val NOTIFICATION_CHANNEL_NAME = "SimpMusic Playback Notification"
    const val NOTIFICATION_CHANNEL_ID = "SimpMusic Playback Notification ID"
}

private const val MUSICMAX_ACTIVITY_PACKAGE_NAME = "com.example.amusic.MainActivity"

@OptIn(UnstableApi::class)
class MusicService : MediaSessionService() {

    lateinit var player: ExoPlayer
    lateinit var mediaSession: MediaSession
    lateinit var customMediaSessionCallback: CustomMediaSessionCallback
    lateinit var musicNotificationProvider: MusicNotificationProvider

    private val _currentMediaId = MutableStateFlow("")
    private val currentMediaId = _currentMediaId.asStateFlow()


    //构建 mediasess  和  play 最佳方法
    override fun onCreate() {
        super.onCreate()
//        setMediaNotificationProvider(
//            DefaultMediaNotificationProvider(
//                this,
//                { MEDIA_NOTIFICATION.NOTIFICATION_ID },
//                MEDIA_NOTIFICATION.NOTIFICATION_CHANNEL_ID,
//                R.string.app_name
//            )
//                .apply {
//                    setSmallIcon(R.mipmap.icon_main)
//                }
//        )

        musicNotificationProvider = MusicNotificationProvider(this)
        customMediaSessionCallback = CustomMediaSessionCallback()

        val audioAttributes = AudioAttributes.Builder()
            .setContentType(C.AUDIO_CONTENT_TYPE_MUSIC)
            .setUsage(C.USAGE_MEDIA)
            .build()

        player = ExoPlayer.Builder(this)
            //自动处理音频焦点
            .setAudioAttributes(audioAttributes, true)
            //自动暂停播放
            .setHandleAudioBecomingNoisy(true)
            .setWakeMode(C.WAKE_MODE_NETWORK)
            .setSeekForwardIncrementMs(5000)
            .setSeekBackIncrementMs(5000)
            .build()

        mediaSession = MediaSession.Builder(this, player)
            .setCallback(customMediaSessionCallback)
            .setSessionActivity(
                PendingIntent.getActivity(
                    this,
                    0,
                    Intent(this, MainActivity::class.java),
                    PendingIntent.FLAG_IMMUTABLE
                )
            ).setBitmapLoader(provideCoilBitmapLoader(this))
            .build()

        setMediaNotificationProvider(musicNotificationProvider)

        val sessionToken = SessionToken(this, ComponentName(this, MusicService::class.java))
        val mediaControllerFuture = MediaController.Builder(this, sessionToken).buildAsync()
        mediaControllerFuture.addListener(
            { mediaControllerFuture.get() },
            MoreExecutors.directExecutor()
        )

    }

    fun provideCoilBitmapLoader(context: Context): CoilBitmapLoader = CoilBitmapLoader(context)
    private inner class PlayerListener : Player.Listener {
        override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
            if (mediaItem == null) return
            _currentMediaId.update { mediaItem.mediaId }
        }
    }

    override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? =
        mediaSession


    override fun onTaskRemoved(rootIntent: Intent?) {
        super.onTaskRemoved(rootIntent)
        val player = mediaSession.player
        if (!player.playWhenReady || player.mediaItemCount == 0 || player.playbackState == Player.STATE_ENDED) {
            player.stop()
            stopSelf()
        }
    }

    override fun onDestroy() {
        mediaSession.run {
            player.release()
            release()
        }
        super.onDestroy()
    }

    fun toggleLike() {
        Log.e("TAG", "点击了 喜欢: ")
    }

    fun toggleClose() {
        Log.e("TAG", "点击了 关闭: ")
    }
}


















